<template>
  <q-page padding>
    <div class="form-container">
      <q-form @submit="onSubmitLogin" class="q-gutter-md">
        <q-select v-model="chapter" :options="chapterOptions" label="分会" emit-value map-options :loading="loading"
          use-input input-debounce="0" @filter="filterAgencies" />
        <q-input v-model="uname" label="姓名" />
        <q-input v-model="password" label="密码" :type="isPwd ? 'password' : 'text'"
          :rules="[val => val && val.length > 0 || '请输入密码']">
          <template v-slot:append>
            <q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isPwd = !isPwd" />
          </template>
        </q-input>
        <!-- 修改按钮部分 -->
        <div class="row justify-center  q-mt-md q-gutter-md">
          <q-btn label="登录" type="submit" color="primary" />
          <q-btn label="注册" color="info" @click="onRegister" />
          <q-btn label="忘记密码" flat color="grey" @click="onForgotPassword" />
        </div>
      </q-form>
    </div>
  </q-page>
</template>

<script>
import { getAgencyList, login, loginWithPassword } from 'src/js/api';

export default {
  data() {
    return {
      uname: '',
      chapter: '',
      chapterOptions: [], // 分会选项列表
      loading: false,     // 加载状态
      password: '',  // 添加密码字段
      isPwd: true    // 控制密码显示/隐藏
    };
  },
  async created() {
    // 组件创建时获取分会列表
    await this.fetchAgencyList();
  },

  methods: {
    filterAgencies(val, update) {
      if (val === '') {
        update(() => {
          this.chapterOptions = this.originalOptions;
        });
        return;
      }

      update(() => {
        const needle = val.toLowerCase();
        this.chapterOptions = this.originalOptions?.filter(
          v => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },
    async fetchAgencyList() {
      try {
        this.loading = true;
        const res = await getAgencyList();
        if (res && res.data) {
          let data = res.data.data.data.list;
          // 假设返回的数据格式为 [{id: 1, name: '分会1'}, ...]
          this.chapterOptions = data.map(item => ({
            label: item.name,
            value: item.name
          }));
          this.originalOptions = this.chapterOptions; // 保存原始选项
        } else {
          this.chapterOptions = [];
          this.originalOptions = []; // 确保原始选项为空
        }
      } catch (error) {
        console.error('获取分会列表失败:', error);
        this.$q.notify({
          type: 'negative',
          message: '获取分会列表失败'
        });
        this.chapterOptions = [];
        this.originalOptions = []; // 确保原始选项为空
      } finally {
        this.loading = false;
      }
    },
    onRegister() {
      // 跳转到注册页面
      this.$router.push({ name: 'RegisterPage' })
    },

    onForgotPassword() {
      // 跳转到忘记密码页面
      this.$router.push({ name: 'ForgotPassword' })
    },
    async onSubmitLogin() {

      // 收集缺少的字段
      const missingFields = [];
      if (!this.uname) missingFields.push('姓名');
      if (!this.chapter) missingFields.push('分会');
      if (!this.password) missingFields.push('密码');

      // 如果有缺少的字段，显示提示
      if (missingFields.length > 0) {
        this.$q.notify({
          type: 'negative',
          message: `请确保以下字段已填写: ${missingFields.join(', ')}`
        });
        return; // 如果有字段为空，停止执行
      }

      let user = {
        uname: this.uname, chapter: this.chapter, password: this.password
      }
      let res = await loginWithPassword(user)
      console.log(res);
      let data = res.data.data
      if (res && !data.code) {
        localStorage.setItem("user", JSON.stringify(user))
        this.$router.push({ "name": "InputContent" })
      } else {
        this.$q.notify({
          type: 'negative',
          message: data.msg
        })
      }
    }
  }
};
</script>
